<template>
  <div :class="['tui-chat', 'tui-chat-h5']">
    <div
      v-if="currentConversationID"
      :class="['tui-chat', 'tui-chat-h5']"
    >
      <MessageList
        ref="messageListRef"
        :class="['tui-chat-message-list', 'tui-chat-h5-message-list']"
        @handleEditor="handleEditor"
        @closeInputToolBar="() => changeToolbarDisplayType('none')"
        :bottomQuickOrder="props.bottomQuickOrder"
        :showBottomQuickOrder="showBottomQuickOrder"
        :toolbarButtonList="props.toolbarButtonList"
        @closeBottomQuickOrder="closeBottomQuickOrder"
        :enableFeedback="props.enableFeedback"
        :enableAINote="props.enableAINote"
        @like="onLike"
        @dislike="onDislike"
      />
      <!-- tiktok 小程序始终显示 toolbarbutton，避免层级问题  -->
      <MessageToolbarButton
        v-if="computedShowToolbarButton"
        :toolbarButtonList="props.toolbarButtonList"
        :class="[isUniPopupShow && 'tui-chat-uni-toolbar-button-hide']"
      />
      <MessageInputToolbar
        v-if="isInputToolbarShow"
        :class="[
          'tui-chat-message-input-toolbar',
          'tui-chat-h5-message-input-toolbar',
          isUniFrameWork && 'tui-chat-uni-message-input-toolbar',
          isUniPopupShow && 'tui-chat-uni-message-input-toolbar-hide'
        ]"
        :displayType="inputToolbarDisplayType"
        @insertEmoji="insertEmoji"
        @changeToolbarDisplayType="changeToolbarDisplayType"
        @scrollToLatestMessage="scrollToLatestMessage"
      />
      <MessageInput
        ref="messageInputRef"
        :class="[
          'tui-chat-message-input',
          'tui-chat-h5-message-input',
          isUniFrameWork && !isH5 && 'tui-chat-uni-message-input',
          isWeChat && 'tui-chat-wx-message-input',
          isUniPopupShow && 'tui-chat-uni-message-input-hide',
        ]"
        :isMuted="isMuted"
        :muteText="muteText"
        :canSendAudio="props.canSendAudio"
        placeholder=""
        :inputToolbarDisplayType="inputToolbarDisplayType"
        @changeToolbarDisplayType="changeToolbarDisplayType"
        @messageSent="onMessageSent"
      />
      <FeedbackModal
        ref="feedbackModalRef"
        v-show="showFeedbackModal"
        @close="() => { showFeedbackModal = false }"
      />
      <CenterDiaglog ref="centerDialogRef" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import vue from '../../adapter-vue';
import TUIChatEngine, {IMessageModel, StoreName, TUIStore, TUITranslateService,} from '../../@aidesk/uikit-engine';
import MessageList from './message-list/index-uniapp.vue';
import MessageInput from './message-input/index-uniapp.vue';
import MessageInputToolbar from './message-input-toolbar/index-uniapp.vue';
import { isApp, isH5, isTikTok, isUniFrameWork, isWeChat } from '../../utils/env';
import { InputToolbarModel, QuickOrderModel, ToolbarButtonModel, ToolbarDisplayType } from '../../interface';
import { isSupportedLang } from '../../utils/';
import Log from '../../utils/logger';
import MessageToolbarButton from './message-toolbar-button/index.vue';
import TUILocales from '../../locales';
import { Toast, TOAST_TYPE } from "../common/Toast/index-uniapp";
import state from '../../utils/state.js';
import { isNonEmptyObject, updateCustomStore } from '../../utils/utils';
import FeedbackModal from './feedback-modal/index.vue';
import CenterDiaglog from "./center-dialog.vue";

const { ref, onMounted, onUnmounted, computed } = vue;
const feedbackModalRef = ref();
const centerDialogRef = ref();
const showFeedbackModal = ref(false);
const emits = defineEmits(['closeChat']);
const currentConversationID = ref();
const inputToolbarDisplayType = ref<ToolbarDisplayType>('none');
const messageInputRef = ref();
const messageListRef = ref<InstanceType<typeof MessageList>>();
const isMuted = ref(false);
const muteText = ref('');
const isUniPopupShow = ref<boolean>(false);
const languages = Object.keys(TUILocales);
const showBottomQuickOrder = ref(false);
const computedShowToolbarButton = computed(() => {
  if (isTikTok) {
    if (Array.isArray(props.toolbarButtonList) && props.toolbarButtonList.length > 0) {
      return true;
    }
    return false;
  }
  return !showBottomQuickOrder.value;
});

interface IProps {
  robotLang?:string;
  userLang?:string;
  canSendAudio?:boolean;
  toolbarButtonList?:ToolbarButtonModel[];
  showAvatar?: number;
  robotAvatar?: string;
  staffAvatar?: string;
  userAvatar?: string;
  showNickName?: number;
  robotNickName?: string;
  staffNickName?: string;
  userNickName?: string;
  inputToolbarList?: InputToolbarModel[];
  showReadStatus?: number;
  showTyping?: number;
  bottomQuickOrder?: QuickOrderModel;
  enableFeedback?: number;
  enableAINote?: number;
  enableURLDetection?: number;
  showPrompt?: number;
}

const props = withDefaults(defineProps<IProps>(), {
  robotLang: '',
  userLang: '',
  canSendAudio: false,
  toolbarButtonList: () => [] as ToolbarButtonModel[],
  showReadStatus: 1,
  showAvatar: 1,
  robotAvatar: '',
  staffAvatar: '',
  userAvatar: '',
  showNickName: 0,
  robotNickName: '',
  staffNickName: '',
  userNickName: '',
  inputToolbarList: () => [] as InputToobarModel[],
  showTyping: 0,
  enableFeedback: 0,
  enableAINote: 1,
  enableURLDetection: 0,
  showPrompt: 1,
});

const convertLanguageToLowercase = (language) => {
  if (!language) {
    return 'zh';
  }
  let lowercase = language.toLowerCase();
  if (lowercase === 'zh-cn' || lowercase === 'zh_cn') {
    lowercase = 'zh';
  } else if (lowercase === 'zh-tw' || lowercase === 'zh-hk') {
    lowercase = 'zh_tw';
  }
  return lowercase;
};

const initLanguage = () => {
  Log.i(`initLanguage ${props.userLang}`);
  TUITranslateService.provideLanguages({ ...TUILocales });
  TUITranslateService.useI18n();
  let language;
  if (props.userLang !== '') {
    language = convertLanguageToLowercase(props.userLang);
    if (!languages.includes(language)) {
      Log.w(`userLang:${props.userLang} is not supported`);
      language = 'en';
    }
  } else {
    if (isApp) {
      const { osLanguage } = uni.getDeviceInfo();
      Log.i(`initLanguage osLanguage:${osLanguage}`);
      language = convertLanguageToLowercase(osLanguage);
    } else if (isWeChat) {
      language = 'zh';
    } else if (navigator) {
      language = convertLanguageToLowercase(navigator.language);
    }

    if (!languages.includes(language)) {
      language = 'en';
    }
  }
  state.set('currentLanguage', language);
  TUITranslateService.changeLanguage(language);
};

const setAvatarNickName = () => {
  state.set('avatarNickName',{
    showAvatar: props.showAvatar,
    showNickName: props.showNickName,
    userAvatar: props.userAvatar,
    staffAvatar: props.staffAvatar,
    robotAvatar: props.robotAvatar,
    userNickName: props.userNickName,
    staffNickName: props.staffNickName,
    robotNickName: props.robotNickName
  });
};

const setShowReadStatus = () => {
  state.set('showReadStatus', props.showReadStatus);
};

const setShowTyping = () => {
  state.set('showTyping', props.showTyping);
};

const setShowBottomQuickOrder = () => {
  if (isNonEmptyObject(props.bottomQuickOrder)) {
    showBottomQuickOrder.value = true;
  }
};

const setEnableURLDetection = () => {
  state.set('enableURLDetection', props.enableURLDetection);
}

const setShowPrompt = () => {
  state.set('showPrompt', props.showPrompt);
}

// 小程序平台暂不支持切换语言
if (isWeChat || isTikTok) {
  state.set('currentLanguage', 'zh');
} else {
  initLanguage();
}
setAvatarNickName();
setShowReadStatus();
setShowTyping();
setShowBottomQuickOrder();
setEnableURLDetection();
setShowPrompt();

onMounted(() => {
  const logPrefix = 'CustomerServiceChat onMounted.';
  Log.l(`${logPrefix} engineReady:${TUIChatEngine.isReady()} props:`, props);
  if (props.robotLang && !isSupportedLang(props.robotLang)) {
    Log.w(`${logPrefix} robotLang:${props.robotLang} is not supported`);
  }

  setShowBottomQuickOrder();

  TUIStore.watch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
  });
  TUIStore.watch(StoreName.USER, {
    kickedOut: onKickedOut,
  });
  TUIStore.watch(StoreName.CUSTOM, {
    formPopup: handlePopup,
    centerDialog: handleCenterDialog,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
  });
  TUIStore.unwatch(StoreName.USER, {
    kickedOut: onKickedOut,
  });
  TUIStore.unwatch(StoreName.CUSTOM, {
    formPopup: handlePopup,
  });
  // 卸载时清除当前会话 ID 的记录
  TUIStore.update(StoreName.CONV, 'currentConversationID', '');
  updateCustomStore('formPopup', false);
  showFeedbackModal.value = false;
  isUniPopupShow.value = false;
});

const isInputToolbarShow = computed<boolean>(() => {
  return isUniFrameWork ? inputToolbarDisplayType.value !== 'none' : true;
});

const insertEmoji = (emojiObj: object) => {
  messageInputRef.value?.insertEmoji(emojiObj);
};

const onMessageSent = () => {
  // 发送消息后列表滚动到底部
  messageListRef.value?.scrollToLatestMessage();
};

const handleEditor = (message: IMessageModel, type: string) => {
  if (!message || !type) return;
  switch (type) {
    case 'reference':
      // todo
      break;
    case 'reply':
      // todo
      break;
    case 'reedit':
      if (message?.payload?.text) {
        messageInputRef?.value?.reEdit(message?.payload?.text);
      }
      break;
    default:
      break;
  }
};

function changeToolbarDisplayType(type: ToolbarDisplayType) {
  inputToolbarDisplayType.value
    = inputToolbarDisplayType.value === type ? 'none' : type;
  if (inputToolbarDisplayType.value !== 'none' && isUniFrameWork) {
    uni.$emit('scroll-to-bottom');
  }

  if (isTikTok) {
    messageListRef.value?.adjustHeightInTikTok(inputToolbarDisplayType.value);
  }
}

function scrollToLatestMessage() {
  messageListRef.value?.scrollToLatestMessage();
}

function onKickedOut(type: string) {
  if (type) {
    isMuted.value = true;
    // muteText.value = TUITranslateService.t('TUIChat.账号被强制下线');
    Toast({
      message: TUITranslateService.t('TUIChat.账号被强制下线'),
      type: TOAST_TYPE.ERROR,
      duration: 30000,
    });
  }
}

function onCurrentConversationIDUpdate(conversationID: string) {
  if (!conversationID) {
    return;
  }

  currentConversationID.value = conversationID;
  TUIStore.update(StoreName.CUSTOM, 'activeConversation', {
    conversationID,
    robotLang: props.robotLang && isSupportedLang(props.robotLang) ? props.robotLang : undefined,
  });
}

function handlePopup(displayFlag: boolean) {
  if (isH5) {
    return;
  }
  // app和小程序表单底部弹出时需要隐藏 message-input 和 toolbar-button，避免层级遮罩问题（设置 z-index 无效）
  isUniPopupShow.value = displayFlag;
  if (!displayFlag) {
    // 表单隐藏时消息列表滚动到底部
    messageListRef.value?.scrollToLatestMessage();
  }
}

function handleCenterDialog(promptType: string) {
  // 只有要上架应用市场的 app 才需要这个权限申请的弹窗提醒
  if (isApp && (props.showPrompt === 1) && centerDialogRef.value) {
    centerDialogRef.value.show(promptType);
  }
}

function closeBottomQuickOrder() {
  showBottomQuickOrder.value = false;
}

function onLike(messageInfo: Object) {
  feedbackModalRef.value.onLike(messageInfo);
}

function onDislike(messageInfo: Object) {
  showFeedbackModal.value = true;
  feedbackModalRef.value.onDislike(messageInfo);
}
</script>

<style scoped lang="scss" src="./style/index.scss"></style>
